<template>
  <div class="business-report">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="统计时间" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select
            v-model="searchForm.businessType"
            placeholder="请选择业务类型"
            clearable
            style="width: 120px"
          >
            <el-option label="贷款申请" value="apply" />
            <el-option label="贷款审批" value="approval" />
            <el-option label="贷款发放" value="disburse" />
            <el-option label="贷款回收" value="collect" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>申请金额</span>
              <el-tag size="small">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">¥ {{ formatAmount(stats.applyAmount) }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.applyRate >= 0 ? 'up' : 'down'">
                {{ stats.applyRate >= 0 ? '+' : '' }}{{ stats.applyRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>发放金额</span>
              <el-tag size="small">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">¥ {{ formatAmount(stats.disburseAmount) }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.disburseRate >= 0 ? 'up' : 'down'">
                {{ stats.disburseRate >= 0 ? '+' : '' }}{{ stats.disburseRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>回收金额</span>
              <el-tag size="small">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">¥ {{ formatAmount(stats.collectAmount) }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.collectRate >= 0 ? 'up' : 'down'">
                {{ stats.collectRate >= 0 ? '+' : '' }}{{ stats.collectRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>回收率</span>
              <el-tag size="small">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.collectRate }}%</div>
            <div class="stat-compare">
              环比
              <span :class="stats.collectRateChange >= 0 ? 'up' : 'down'">
                {{ stats.collectRateChange >= 0 ? '+' : '' }}{{ stats.collectRateChange }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">业务金额趋势</div>
          </template>
          <div class="chart-content" ref="amountChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">业务笔数趋势</div>
          </template>
          <div class="chart-content" ref="countChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">业务类型分布</div>
          </template>
          <div class="chart-content" ref="typeChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">业务状态分布</div>
          </template>
          <div class="chart-content" ref="statusChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细数据 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">业务明细</div>
      </template>
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="date" label="日期" width="100" />
        <el-table-column prop="businessType" label="业务类型" width="100">
          <template #default="scope">
            <el-tag :type="getBusinessTypeTag(scope.row.businessType)">
              {{ getBusinessTypeText(scope.row.businessType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="业务金额" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="业务笔数" width="100" />
        <el-table-column prop="successRate" label="成功率" width="100">
          <template #default="scope">
            {{ scope.row.successRate }}%
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { reportApi } from '@/api/report'

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  businessType: ''
})

// 统计数据
const stats = reactive({
  applyAmount: 0,
  applyRate: 0,
  disburseAmount: 0,
  disburseRate: 0,
  collectAmount: 0,
  collectRate: 0,
  collectRateChange: 0
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 图表引用
const amountChartRef = ref(null)
const countChartRef = ref(null)
const typeChartRef = ref(null)
const statusChartRef = ref(null)

// 图表实例
let amountChart = null
let countChart = null
let typeChart = null
let statusChart = null

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await reportApi.getBusinessStats()
    if (res.code === 200) {
      Object.assign(stats, res.data)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const res = await reportApi.getBusinessCharts()
    if (res.code === 200) {
      const { months, amountTrend, countTrend, typeDistribution, statusDistribution } = res.data
      updateCharts(months, amountTrend, countTrend, typeDistribution, statusDistribution)
    }
  } catch (error) {
    console.error('获取图表数据失败', error)
  }
}

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await reportApi.getBusinessList(params)
    if (res.code === 200) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败', error)
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = (months, amountTrend, countTrend, typeDistribution, statusDistribution) => {
  // 业务金额趋势图
  amountChart.setOption({
    xAxis: {
      data: months
    },
    series: [
      {
        name: '申请金额',
        data: amountTrend.apply
      },
      {
        name: '发放金额',
        data: amountTrend.disburse
      },
      {
        name: '回收金额',
        data: amountTrend.collect
      }
    ]
  })

  // 业务笔数趋势图
  countChart.setOption({
    xAxis: {
      data: months
    },
    series: [
      {
        name: '申请笔数',
        data: countTrend.apply
      },
      {
        name: '发放笔数',
        data: countTrend.disburse
      },
      {
        name: '回收笔数',
        data: countTrend.collect
      }
    ]
  })

  // 业务类型分布图
  typeChart.setOption({
    series: [
      {
        data: typeDistribution
      }
    ]
  })

  // 业务状态分布图
  statusChart.setOption({
    series: [
      {
        data: statusDistribution
      }
    ]
  })
}

// 初始化图表
const initCharts = () => {
  // 业务金额趋势图
  amountChart = echarts.init(amountChartRef.value)
  amountChart.setOption({
    title: {
      text: '业务金额趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['申请金额', '发放金额', '回收金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 万'
      }
    },
    series: [
      {
        name: '申请金额',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '发放金额',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '回收金额',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  })

  // 业务笔数趋势图
  countChart = echarts.init(countChartRef.value)
  countChart.setOption({
    title: {
      text: '业务笔数趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['申请笔数', '发放笔数', '回收笔数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '申请笔数',
        type: 'bar',
        data: []
      },
      {
        name: '发放笔数',
        type: 'bar',
        data: []
      },
      {
        name: '回收笔数',
        type: 'bar',
        data: []
      }
    ]
  })

  // 业务类型分布图
  typeChart = echarts.init(typeChartRef.value)
  typeChart.setOption({
    title: {
      text: '业务类型分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['贷款申请', '贷款审批', '贷款发放', '贷款回收']
    },
    series: [
      {
        name: '业务类型',
        type: 'pie',
        radius: '50%',
        data: []
      }
    ]
  })

  // 业务状态分布图
  statusChart = echarts.init(statusChartRef.value)
  statusChart.setOption({
    title: {
      text: '业务状态分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['已完成', '处理中', '已取消', '已拒绝']
    },
    series: [
      {
        name: '业务状态',
        type: 'pie',
        radius: ['30%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    amountChart?.resize()
    countChart?.resize()
    typeChart?.resize()
    statusChart?.resize()
  })
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchTableData()
}

// 重置
const handleReset = () => {
  searchForm.dateRange = []
  searchForm.businessType = ''
  handleSearch()
}

// 导出
const handleExport = async () => {
  try {
    const data = {
      startDate: searchForm.dateRange ? searchForm.dateRange[0] : '',
      endDate: searchForm.dateRange ? searchForm.dateRange[1] : '',
      businessType: searchForm.businessType,
      exportType: 'detail'
    }
    await reportApi.exportBusinessReport(data)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败', error)
    ElMessage.error('导出失败')
  }
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

// 格式化金额
const formatAmount = (amount) => {
  return amount ? (amount / 10000).toFixed(2) + '万' : '0'
}

// 获取业务类型标签类型
const getBusinessTypeTag = (type) => {
  const map = {
    apply: '',
    approval: 'warning',
    disburse: 'success',
    collect: 'info'
  }
  return map[type]
}

// 获取业务类型文本
const getBusinessTypeText = (type) => {
  const map = {
    apply: '贷款申请',
    approval: '贷款审批',
    disburse: '贷款发放',
    collect: '贷款回收'
  }
  return map[type]
}

// 组件挂载后初始化图表和获取数据
onMounted(async () => {
  initCharts()
  await fetchStats()
  await fetchChartData()
  await fetchTableData()
})
</script>

<style scoped>
.business-report {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stat-content {
    text-align: center;

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .stat-compare {
      color: #666;
      font-size: 14px;

      .up {
        color: #67c23a;
      }

      .down {
        color: #f56c6c;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  .chart-header {
    font-weight: bold;
  }

  .chart-content {
    height: 300px;
  }
}

.table-card {
  margin-bottom: 20px;

  .table-header {
    font-weight: bold;
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 